define('common:widget/ui/ai/aiDialog/index', function(require, exports, module) {

  /**
   * @file AI工具弹窗
   * @author donghualei
   */
  
  var san = require('common:widget/ui/ai/san');
  var $ = require('common:widget/ui/base/base');
  var Button = require('common:widget/ui/ai/button/index');
  var Header = require('common:widget/ui/ai/header/index');
  var Content = require('common:widget/ui/ai/content/index');
  
  var EDITSTATUS = {
      DEFAULT: 'default',
      EDIT: 'edit',
      LOADING: 'loading',
      COMPLETE: 'complete',
      FAIL: 'fail'
  };
  
  var TOOLTYPE = {
      WATERMARK: 'watermark',
      MANUAL: 'manual',
      REPAIR: 'repair',
      EXPAND: 'expand',
      REPLACE: 'replace',
      REBORN: 'reborn',
      SIMILAR: 'similar',
      REMOVE: 'remove'
  };
  
  var TOOLTYPEMAP = {
      // AI去水印
      [TOOLTYPE.WATERMARK]: '1',
      // 手动去水印
      [TOOLTYPE.MANUAL]: '2',
      // 画质修复
      [TOOLTYPE.REPAIR]: '3',
      // AI扩图
      [TOOLTYPE.EXPAND]: '4',
      // 局部替换
      [TOOLTYPE.REPLACE]: '5',
      // AI重绘
      [TOOLTYPE.REBORN]: '6',
      // AI相似图
      [TOOLTYPE.SIMILAR]: '7',
      // 涂抹消除
      [TOOLTYPE.REMOVE]: '8'
  };
  
  var surveyController = require('common:widget/ui/ai/survey/controller');
  var PAGE = require('common:widget/ui/ai/survey/constant');
  
  return san.defineComponent({
      template: ''
          +   '<div s-if="originImg && originImg.src" class="ai-edit-wraper">'
          +       '<m-header '
          +           's-ref="header"'
          +           'select-type="{{selectType}}"'
          +           'page-fr="{{pageFr}}"'
          +           'logid="{{logid}}"'
          +           'search-id="{{searchId}}"'
          +           'current-status="{{currentStatus}}"'
          +           'origin-img="{{originImg}}"'
          +           'query="{{query}}"'
          +           'on-exit="handleExit"'
          +           'on-reset="handleReset"'
          +           'on-undo-redo-click="handleUndoRedoClick"'
          +       '/>'
          +       '<m-content '
          +           's-ref="content"'
          +           'select-type="{{selectType}}"'
          +           'btn-list="{{btnList}}"'
          +           'page-fr="{{pageFr}}"'
          +           'logid="{{logid}}"'
          +           'search-id="{{searchId}}"'
          +           'ext-multi="{{extMulti}}"'
          +           'ext-ratio="{{extRatio}}"'
          +           'similar-default="{{similarDefault}}"'
          +           'reborn-default="{{rebornDefault}}"'
          +           'origin-img="{{originImg}}"'
          +           'thumb-img="{{thumbImg}}"'
          +           'query="{{query}}"'
          +           'canvas-image="{{canvasImage}}"'
          +           'tool-type="{{toolType}}"'
          +           'tool-type-map="{{toolTypeMap}}"'
          +           'edit-status="{{editStatus}}"'
          +           'current-status="{{currentStatus}}"'
          +           'down-link="{{downLink}}"'
          +           'on-select-type="handleSelectType"'
          +           'on-click-manual="handleManual"'
          +           'on-change-edit-status="getEditStatus"'
          +           'on-update-canvas-image="updateCanvasImage"'
          +           'on-change-login-status="updateLoginStatus"'
          +           'on-undo-redo-status="handleUndoRedoStatus"'
          +       '/>'
          +   '</div>',
      components: {
          'ui-button': Button,
          'm-header': Header,
          'm-content': Content
      },
      initData: function () {
          return {
              toolType: TOOLTYPE,
              toolTypeMap: TOOLTYPEMAP,
              editStatus: EDITSTATUS,
              currentStatus: EDITSTATUS.EDIT,
              selectType: '-1',
              originImg: {},
  
              imgInfo: {},
              query: '',
  
              // 更新画布的数据
              canvasImage: {},
              btnList: [],
              extRatio: [],
              extMulti: [],
              similarDefault: 5,
              rebornDefault: 5,
  
              pageFr: '',
              logid: '',
              searchId: '',
              downLink: '',
              loginStatusChanged: false,
  
              // 公共日志参数
              logExtra: {}
          };
      },
      messages: {
          'send-log': function (arg) {
              var logValue = arg.value;
              this.sendLog(logValue.type, logValue.value, logValue.ext);
          }
      },
      attached: function () {
          var editData = this.data.get('editData');
          var aiPicHelperAbilities = editData.aiPicHelperAbilities;
          var extMulti = editData.extMulti;
          var extRatio = editData.extRatio;
          var similarDefault = editData.defaultCreateLevel && editData.defaultCreateLevel.value || 5;
          var rebornDefault = this.clarityMap(this.data.get('imgInfo').clarity);
          this.data.set('btnList', aiPicHelperAbilities);
          this.data.set('extMulti', extMulti);
          this.data.set('extRatio', extRatio);
          this.data.set('similarDefault', similarDefault);
          this.data.set('rebornDefault', rebornDefault);
          var _this = this;
          this.checkImg().then(function (res) {
              var width = res.width;
              var height = res.height;
              var canvasImageInfo = {
                  src: res.src,
                  width,
                  height
              };
              _this.data.set('canvasImage', canvasImageInfo);
  
              _this.nextTick(function () {
                  _this.sendLog('show', 'edit', {
                      function: _this.data.get('selectType'),
                      edit_status: _this.data.get('currentStatus')
                  });
              });
          });
      },
  
      getImgRect: function (url) {
          var pro = new $.Deferred();
          var img = new Image();
          img.onload = function (res) {
              pro.resolve({
                  src: url,
                  width: img.width,
                  height: img.height
              });
          };
          img.src = url;
  
          return pro;
      },
  
      checkImg: function () {
          var pro = new $.Deferred();
          var imgInfo = this.data.get('imgInfo');
          var objURL = imgInfo.objURL || imgInfo.objurl;
          var thumbURL = imgInfo.thumbURL || '';
          var imgType = imgInfo.imgType || '';
  
          var _this = this;
          this.getImgRect(thumbURL).then(function (res) {
              var width = res.width;
              var height = res.height;
              _this.data.set('thumbImg', {
                  src: thumbURL,
                  width,
                  height
              });
              // objURL 原图
              // thumbURL 缩略图
  
              var img = new Image();
              img.onload = function () {
                  var originImgInfo = {
                      src: objURL,
                      width: img.width,
                      height: img.height,
                      // 画布上展示的是否是原图
                      isOrigin: imgType !== 'gif'
                  };
                  pro.resolve(originImgInfo);
                  _this.data.set('originImg', originImgInfo);
              };
              img.onerror = function () {
                  var thumbInfo = {
                      src: thumbURL,
                      width,
                      height,
                      isOrigin: false
                  };
                  // 图片加载完成后的操作
                  pro.resolve(thumbInfo);
                  // 失败的时候需要用缩略图
                  _this.data.set('originImg', thumbInfo);
              };
              img.src = objURL;
          });
  
          return pro;
      },
  
      sendLog: function (type, value, extra) {
          var originImg = this.data.get('originImg');
          var query = this.data.get('query');
          var pageFr = this.data.get('pageFr');
          var logid = this.data.get('logid');
          var searchId = this.data.get('searchId');
  
          var ext = $.extend({}, {
              image: originImg.src,
              query,
              page_fr: pageFr,
              search_id: searchId,
              logid
          }, this.data.get('logExtra'));
  
          for (var key in extra) {
              if (extra.hasOwnProperty(key)) {
                  ext[key] = extra[key];
              }
          }
  
          window.ubcLogger.send({
              type,
              value,
              ext
          });
      },
  
      /**
       * 处理重置
       */
      handleReset: function () {
          var originImg = this.data.get('originImg');
          this.data.set('canvasImage', originImg);
          this.data.set('currentStatus', 'default');
          this.data.set('selectType', '-1');
          var contentNode = this.ref('content') || null;
          // 重置后需要清空历史
          contentNode && contentNode.clearImgHistory();
      },
  
      /**
       * 传达header中的undo redo点击操作，通知content处理
       */
      handleUndoRedoClick: function (params) {
          var contentNode = this.ref('content') || null;
          contentNode && contentNode.handleUndoRedoClick(params.type);
      },
  
      /**
       * 传达undo redo状态（高亮或者不高亮），通知header
       */
      handleUndoRedoStatus: function (params) {
          var headerNode = this.ref('header') || null;
          headerNode && headerNode.handleUndoRedoStatus(params);
      },
  
      handleExit: function () {
  
          // 如果出现过登录状态变更（未登录->登录），则退出时刷新页面
          if (this.data.get('loginStatusChanged')) {
              window.location.reload();
          }
          else {
              this.fire('exit');
          }
      },
  
      updateLoginStatus: function (status) {
          // 记录登录状态变更
          this.data.set('loginStatusChanged', status);
      },
  
      getEditStatus: function (status) {
          this.data.set('currentStatus', status);
          if (surveyController.displayParams.page === PAGE.EDIT) {
              surveyController.addExtra({edit_status: status});
          }
      },
  
      handleManual: function (resType) {
          this.data.set('selectType', TOOLTYPEMAP[TOOLTYPE.MANUAL]);
          if (resType > 0) {
              this.data.set('currentStatus', 'edit');
          }
      },
  
      handleSelectType: function (type) {
          this.data.set('selectType', type);
      },
  
      updateCanvasImage: function (img) {
          this.data.set('canvasImage', img);
      },
  
      // 清晰度为空返回5 其余根据范围返回映射的1-6的值
      clarityMap: function (num) {
          if (!num) {
              return 5;
          }
          var rebornDefault = 5;
          if (num < 20) {
              rebornDefault = 6;
          } else if (num < 30 && num >= 20) {
              rebornDefault = 5;
          } else if (num < 40 && num >= 30) {
              rebornDefault = 4;
          } else if (num < 70 && num >= 40) {
              rebornDefault = 3;
          } else if (num < 80 && num >= 70) {
              rebornDefault = 2;
          } else {
              rebornDefault = 1;
          }
          return rebornDefault;
      }
  });
  

});
